package test

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func Update(mongo *mongo.Database, ctx context.Context) {
	// 更新id
	findFilter1 := bson.M{"add1list.text": "hello3"}
	updateFilter1 := bson.M{"$set": bson.M{"id": 10}}
	result1, _ := mongo.Collection("test").UpdateOne(ctx, findFilter1, updateFilter1)
	fmt.Println(result1.MatchedCount, result1.ModifiedCount)
	fmt.Println("1~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

	// 更新指定字段，详见：https://www.mongodb.com/docs/manual/reference/operator/update/positional-filtered/#mongodb-update-up.---identifier--
	findFilter2 := bson.M{"add1list.text": "hello3"}                                      // 确保后续修改的文档具有add1list.text字段
	updateFilter2 := bson.M{"$set": bson.M{"add1list.$[elem].text": "helloUpdate"}}       // 将指定字段的内容更新
	arrayFilters1 := options.ArrayFilters{Filters: bson.A{bson.M{"elem.text": "hello3"}}} // 设置条件匹配想要的字段，elem就变成后面的占位符，数组的下标
	mongo.Collection("test").UpdateMany(ctx, findFilter2, updateFilter2, options.Update().SetArrayFilters(arrayFilters1))

	findFilter3 := bson.M{"add1list.text": "helloUpdate"}

	// 验证结果
	cur, _ := mongo.Collection("test").Find(ctx, findFilter3)
	// 遍历数据
	for cur.TryNext(ctx) {
		result := cur.Current.String()
		fmt.Println(result)
	}
	fmt.Println("2~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
}
